package com.sensetime.bi.senselink.server.entity;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Getter
@Setter
public class Player {
    // 当前服务作为服务端收到的代理请求消息
    private RtspRequestMsg request;

    private Channel connection;

    public void sendRespnse(Object msg) {
        ChannelFuture channelFuture;
        if (msg instanceof RtspResponsetMsg) {
            String response = getResponse((RtspResponsetMsg) msg);
            channelFuture = connection.writeAndFlush(response);
            log.debug("send msg to player service:" + connection.remoteAddress() + ", \n" + response) ;
        } else {
            log.debug("send msg to player service:" + connection.remoteAddress() + "\n") ;
            channelFuture = connection.writeAndFlush(msg);
        }

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.error("from {} send msg to player service:{} error! reason:{}" , connection.localAddress(), connection.remoteAddress(), future.cause());
                    if (!connection.isActive()) {
                        log.error("player service:{} disconnected!" , connection.remoteAddress());
                        // 关闭媒体
                        connection.close();
                    }
                }
            }
        });
    }

    /**
     * RTSP/1.0 200 OK
     * CSeq:3
     * Content-Base: rtsp://10.4.10.135:9554/test.mp4/
     * Content-Type: application/sdp
     */
    private String getResponse(RtspResponsetMsg msg) {
        String[] lines = msg.getLines();
        StringBuilder stringBuilder = new StringBuilder();
        for (String line : lines) {
            if (line.trim().toLowerCase().startsWith("cseq")) {
                stringBuilder.append("CSeq: ").append(request.getCSEQ());
            } else if (line.trim().toLowerCase().startsWith("content-base")) {
                stringBuilder.append("Content-Base: ").append(request.getURL());
            } else {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        String aa = "ADVB";
        System.out.println(aa.toLowerCase());
        System.out.println(aa);
    }
}
